package demo.kafka.sb.kafka;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
@Slf4j
public class KafkaConsumer {

    //在分布式环境中,同一消费组的不同实例共用一个offset, 不同实例不会重复消费同一个消息
    //在分布式环境中,不同消费组的不同实例各用一个offset, 不同实例会重复消费同一个消息
    @KafkaListener(topics = KafkaProducer.TOPIC_TEST, groupId = KafkaProducer.TOPIC_GROUP1)
    public void topic_test(ConsumerRecord<?, ?> record, Acknowledgment ack, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {

        Optional message = Optional.ofNullable(record.value());
        if (message.isPresent()) {
            Object msg = message.get();
            log.info("topic_test 消费了： Topic:" + topic + ",Message:" + msg);
            ack.acknowledge();
        }
    }

    @KafkaListener(topics = KafkaProducer.TOPIC_TEST, groupId = KafkaProducer.TOPIC_GROUP2)
    public void topic_test1(ConsumerRecord<?, ?> record, Acknowledgment ack, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {

        Optional message = Optional.ofNullable(record.value());
        if (message.isPresent()) {
            Object msg = message.get();
            log.info("topic_test1 消费了： Topic:" + topic + ",Message:" + msg);
            ack.acknowledge();
        }
    }

    //该topic有两个分区，如果启动一个消费者，该消费者会同时消费两个分区，但是同一个group中，每个分区仍然只能被一个消费者消费
    //如果同时启动两个消费者，这两个消费者有很大可能平分两个分区，这取决于kafka的分区分配策略。
    //消息落到具体分区后，只能由消费那个分区的消费者去消费
    @KafkaListener(topics = "topic-2p", groupId = "topic-2p-group")
    public void topic2p(ConsumerRecord<?, ?> record, Acknowledgment ack, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {

        Optional message = Optional.ofNullable(record.value());
        if (message.isPresent()) {
            Object msg = message.get();
            log.info("topic2p 消费了： Topic:" + topic + ",Message:" + msg + ", partition=" + record.partition()+", offset="+record.offset());
            ack.acknowledge();
        }
    }
}
